﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Web.Mvc;
using Autofac;
using Newtonsoft.Json.Linq;
using Pay.Core;
using Pay.DTO;
using Pay.DTO.chpay;
using Pay.DTO.mpay;
using Pay.DTO.xsft;
using Pay.DTO.xsft2;
using Pay.DTO.xsft3;
using Pay.IService;
using Pay.Service;
using Pay.TO;
using System.Linq;
using Pay.Core.WeiXin;
using Pay.DTO.htl;
using Pay.DTO.hniao;
using Pay.DTO.cjpay;
using Pay.DTO.tenPay;
using Pay.Service.Pay;
using Pay.DTO.h5;
using System.Collections.Specialized;
using Aop.Api.Util;
using Pay.Core.AliPay;

namespace Pay.Api.Controllers
{
    [RoutePrefix("pay")]
    public class PayController : Controller
    {
        private IComponentContext _iocContext;
        private ISettingService _iSettingService;
        private IBillService _iBillService;
        private IMerchantService _iMerchantService;
        private IPaymentService _iPaymentService;
        private IChargeService _iChargeService;
        private IPayHtmlService _iPayHtmlService;
        private IPayNotifyService _iPayNotifyService;
        private ITransferService _iTransferService;
        private ITokenTransferService _iTokenTransferService;
        private IOrderService _iOrderService;
        private IHtlMallService _iHtlMallService;
        private IHniaoService _iHniaoService;
        private H5Sign _h5Sign;
        private static readonly object sequenceLock = new object();

        public PayController(IComponentContext iocContext, ISettingService iSettingService, IBillService iBillService,
                             IMerchantService iMerchantService, IPaymentService iPaymentService, ITransferService iTransferService,
                             IChargeService iChargeService, IPayHtmlService iPayHtmlService, IPayNotifyService iPayNotifyService,
                             IOrderService iOrderService, IHtlMallService iHtlMallService, IHniaoService iHniaoService,
                             ITokenTransferService iTokenTransferService, H5Sign h5Sign)
        {
            _iocContext = iocContext;
            _iSettingService = iSettingService;
            _iBillService = iBillService;
            _iMerchantService = iMerchantService;
            _iPaymentService = iPaymentService;
            _iChargeService = iChargeService;
            _iPayHtmlService = iPayHtmlService;
            _iPayNotifyService = iPayNotifyService;
            _iTransferService = iTransferService;
            _iOrderService = iOrderService;
            _iHtlMallService = iHtlMallService;
            _iHniaoService = iHniaoService;
            _iTokenTransferService = iTokenTransferService;
            _h5Sign = h5Sign;
        }

        /// <summary>
        /// 同卡同出提交返回URL给APP调用
        /// </summary>
        /// <returns>The front.</returns>
        /// <param name="id">Identifier.</param>
        [Route("jwuct_front/{id}")]
        public ActionResult JwuctFront(string id)
        {
            var obj = _iPayHtmlService.Get(id);
            if (obj != null)
            {
#if DEBUG
                return View("JwuctFrontTest", "", obj);
#else
				return View("JwuctFront", "", obj.html);
#endif
            }
            return View();
        }
        /// <summary>
        /// hxdata同卡同出提交返回URL给APP调用
        /// </summary>
        /// <returns>The front.</returns>
        /// <param name="id">Identifier.</param>
        [Route("hxdata_front/{id}"), Route("hxdata2_front/{id}")]
        public ActionResult hxDataFront(string id)
        {
            var obj = _iPayHtmlService.Get(id);
            if (obj != null)
            {
                return View("JwuctFront", "", obj.html); ;
            }
            return View();
        }

        /// <summary>
        /// html同卡同出提交返回URL给APP调用
        /// </summary>
        /// <returns>The front.</returns>
        /// <param name="id">Identifier.</param>
        [Route("html_front/{id}")]
        public ActionResult HmtlFront(string id)
        {
            var obj = _iPayHtmlService.Get(id);
            if (obj != null)
            {
                return View("JwuctFront", "", obj.html);
            }
            return View();
        }
        /// <summary>
        /// 开联通网关支付返回url给app调用
        /// </summary>
        /// <returns>The front.</returns>
        [Route("klt_front/{id}")]
        public ActionResult KltFront(string id)
        {
            var obj = _iPayHtmlService.Get(id);
            if (obj != null)
            {
                var klt = obj.html.ToObject<klt_gateway_pay>();
                ViewBag.url = obj.charge;
                return View("KltFront", "", klt);
            }
            return View();
        }
        /// <summary>
        /// 开联通网关支付成功跳转页面
        /// </summary>
        /// <returns>The success.</returns>
        [Route("klt_success")]
        public ActionResult KltSuccess()
        {
            return View();
        }
        /// <summary>
        /// 首信易网关支付返回url给app调用
        /// </summary>
        /// <returns>The front.</returns>
        /// <param name="id">Identifier.</param>
        [Route("sxy_front/{id}")]
        public ActionResult SxyFront(string id)
        {
            var obj = _iPayHtmlService.Get(id);
            if (obj != null)
            {
                var klt = obj.html.ToObject<sxy_gateway_pay>();
                ViewBag.url = obj.charge;

                return View("SxyFront", "", klt);
            }
            return View();
        }

        /// <summary>
        /// ky同进同出通道回调通知
        /// </summary>
        /// <returns>The quick notify.</returns>
        /// <param name="id">Identifier.</param>
        /// <param name="data">Model.</param>
        [Route("ky_back_notify/{id}")]
        public async Task<ContentResult> KyQuickNotify(string id, string data)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("ky异步通知了:" + id);
            log.Info("ky异步通知json:" + data);
            var _kySign = new kySign();
            var model = new ky_quick_result();
            if (_kySign.VerifySign(data, out model))
            {
                log.Info("ky异步通知成功:" + model.out_trade_no);
                var result = 0;
                var obj = _iPayHtmlService.Get(id);
                charge_dto charge = null;
                if (obj != null)
                {
                    charge = obj.charge.ToObject<charge_dto>();
                }
                else
                {
                    log.Info("ky－mongodb获取失败:" + model.out_trade_no);
                    return Content("fail");
                }
                var order = _iChargeService.Get(charge.merchant_no, model.out_trade_no);
                //因为同进同出HTML的生成是用mongodb，所以要查数据库订单生成了没有，没有生成则调用返回参数处理
                if (order == null)
                {
                    if (model.status == 1 || model.status == 2)
                    {
                        var dt = DateTime.Now;
                        result = _iChargeService.PaySuceess(obj, model.trade_no, dt);
                        if (result > 0)
                        {
                            var _iPayService = _iocContext.ResolveKeyed<IPayService>(charge.pay_info.pay_channel);
                            var notifyResult = await _iPayService.Notify(charge.merchant_no, charge.order_no);
                            if (notifyResult != "OK")
                            {
                                //创建通知消息对象
                                _iPayNotifyService.Save(new pay_notify_dto
                                {
                                    merchant_no = charge.merchant_no,
                                    order_no = charge.order_no,
                                    pay_channel = charge.pay_info.pay_channel,
                                    type = 1,
                                    status = 2,
                                    create_time = DateTime.Now
                                });
                            }
                            _iPayHtmlService.Remove(id);
                        }
                    }
                    else
                    {
                        result = _iChargeService.PayFail(obj, model.trade_no, model.msg);
                    }
                }
                else
                    return Content("success");
                //回执成功，通道不会再通知
                if (result > 0)
                {
                    return Content("success");
                }
                log.Info("ky-保存数据库订单失败:" + model.out_trade_no);
                return Content("fail");
            }
            log.Info("ky-签名不正确:" + model.out_trade_no);
            return Content("签名不正确");
        }

        [Route("xsft_back_notify/{id}")]
        public async Task<ContentResult> XsftQuickNotify(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("xsft异步通知了:" + id);
            var stream = Request.InputStream;
            var streamReader = new StreamReader(stream);
            var data = streamReader.ReadToEnd();
            log.Info("xsft异步通知数据:" + data);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var arrs = data.Split('&');
            foreach (var arr in arrs)
            {
                var val = arr.Split('=');
                if (val[0] == "resMsg")
                    dic.Add(val[0], Server.UrlDecode(val[1]));
                else
                    dic.Add(val[0], val[1]);
            }
            xsft_notify model = dic.ToJson().ToObject<xsft_notify>();
            var _xsftSign = new XsftSign();
            if (_xsftSign.VerifySign(model))
            {
                log.Info("xsft异步通知成功:" + model.merOrderId);
                var result = 0;
                var charge = _iChargeService.Get(id, model.merOrderId);
                if (charge != null)
                {
                    charge.merchant_no = id;
                    if (model.resCode == "0000")
                    {
                        var dt = DateTime.Now;
                        result = _iChargeService.FailOrUnConfirmToSuceess(charge.merchant_no, model.merOrderId, dt);
                        if (result > 0)
                        {
                            var _iPayService = _iocContext.ResolveKeyed<IPayService>(charge.pay_info.pay_channel);
                            var notifyResult = await _iPayService.Notify(charge.merchant_no, charge.order_no);
                            if (notifyResult != "OK")
                            {
                                //创建通知消息对象
                                _iPayNotifyService.Save(new pay_notify_dto
                                {
                                    merchant_no = charge.merchant_no,
                                    order_no = charge.order_no,
                                    pay_channel = charge.pay_info.pay_channel,
                                    type = 1,
                                    status = 2,
                                    create_time = DateTime.Now
                                });
                            }
                            //回执成功，通道不会再通知
                            return Content("success");
                        }
                    }
                    else
                    {
                        result = _iChargeService.PayFail(charge.merchant_no, model.merOrderId, "", model.resMsg);
                        log.Info("xsft-订单支付失败:" + model.merOrderId);
                        return Content("fail");
                    }
                }
                else
                {
                    log.Info("xsft-保存数据库订单失败:" + model.merOrderId);
                    return Content("fail");
                }
            }
            log.Info("xsft-签名不正确:" + model.merOrderId);
            return Content("签名不正确");
        }

        /// <summary>
        /// xsft2同进同出通道回调通知
        /// </summary>
        /// <returns>The quick notify.</returns>
        /// <param name="id">Identifier.</param>
        [Route("xsft2_back_notify/{id}")]
        public async Task<ContentResult> Xsft2QuickNotify(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("xsft2异步通知了:" + id);
            var stream = Request.InputStream;
            var streamReader = new StreamReader(stream);
            var data = streamReader.ReadToEnd();
            log.Info("xsft2异步通知数据:" + data);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var arrs = data.Split('&');
            foreach (var arr in arrs)
            {
                var val = arr.Split('=');
                if (val[0] == "resMsg")
                    dic.Add(val[0], Server.UrlDecode(val[1]));
                else
                    dic.Add(val[0], val[1]);
            }
            var model = dic.ToJson().ToObject<xsft2_notify>();
            var _xsft2Sign = new Xsft2Sign();
            if (_xsft2Sign.VerifySign(model))
            {
                log.Info("xsft2异步通知成功:" + model.merOrderId);
                var result = 0;
                var obj = _iPayHtmlService.Get(id);
                charge_dto charge = null;
                if (obj != null)
                {
                    charge = obj.charge.ToObject<charge_dto>();
                }
                else
                {
                    log.Info("xsft2－mongodb获取失败:" + model.merOrderId);
                    return Content("fail");
                }
                var order = _iChargeService.Get(charge.merchant_no, model.merOrderId);
                //因为同进同出HTML的生成是用mongodb，所以要查数据库订单生成了没有，没有生成则调用返回参数处理
                if (order == null)
                {
                    if (model.resCode == "0000")
                    {
                        var dt = DateTime.Now;
                        result = _iChargeService.PaySuceess(obj, model.merOrderId, dt);
                        if (result > 0)
                        {
                            var _iPayService = _iocContext.ResolveKeyed<IPayService>(charge.pay_info.pay_channel);
                            var notifyResult = await _iPayService.Notify(charge.merchant_no, charge.order_no);
                            if (notifyResult != "OK")
                            {
                                //创建通知消息对象
                                _iPayNotifyService.Save(new pay_notify_dto
                                {
                                    merchant_no = charge.merchant_no,
                                    order_no = charge.order_no,
                                    pay_channel = charge.pay_info.pay_channel,
                                    type = 1,
                                    status = 2,
                                    create_time = DateTime.Now
                                });
                            }
                            _iPayHtmlService.Remove(id);
                        }
                    }
                    else
                    {
                        result = _iChargeService.PayFail(obj, model.merOrderId, model.resMsg);
                    }
                }
                else
                    return Content("success");
                //回执成功，通道不会再通知
                if (result > 0)
                {
                    return Content("success");
                }
                log.Info("xsft2-保存数据库订单失败:" + model.merOrderId);
                return Content("fail");
            }
            log.Info("xsft2-签名不正确:" + model.merOrderId);
            return Content("签名不正确");
        }

        /// <summary>
        /// xsft3同进同出通道回调通知
        /// </summary>
        /// <returns>The quick notify.</returns>
        /// <param name="id">Identifier.</param>
        [Route("xsft3_back_notify/{id}")]
        public async Task<ContentResult> Xsft3QuickNotify(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("xsft3异步通知了:" + id);
            var stream = Request.InputStream;
            var streamReader = new StreamReader(stream);
            var data = streamReader.ReadToEnd();
            log.Info("xsft3异步通知数据:" + data);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var arrs = data.Split('&');
            foreach (var arr in arrs)
            {
                var val = arr.Split('=');
                if (val[0] == "resMsg")
                    dic.Add(val[0], Server.UrlDecode(val[1]));
                else
                    dic.Add(val[0], val[1]);
            }
            var model = dic.ToJson().ToObject<xsft3_notify>();
            var _xsft3Sign = new Xsft3Sign();
            if (_xsft3Sign.VerifySign(model))
            {
                log.Info("xsft3异步通知成功:" + model.merOrderId);
                var result = 0;
                var obj = _iPayHtmlService.Get(id);
                charge_dto charge = null;
                if (obj != null)
                {
                    charge = obj.charge.ToObject<charge_dto>();
                }
                else
                {
                    log.Info("xsft3－mongodb获取失败:" + model.merOrderId);
                    return Content("fail");
                }
                var order = _iChargeService.Get(charge.merchant_no, model.merOrderId);
                //因为同进同出HTML的生成是用mongodb，所以要查数据库订单生成了没有，没有生成则调用返回参数处理
                if (order == null)
                {
                    if (model.resCode == "0000")
                    {
                        if (model.ordtype.Equals("P") && model.payStatus.Equals("01"))
                        {
                            result = _iChargeService.PaySuceess(obj, model.merOrderId, DateTime.Now);
                            if (result > 0)
                            {
                                var _iPayService = _iocContext.ResolveKeyed<IPayService>(charge.pay_info.pay_channel);
                                var notifyResult = await _iPayService.Notify(charge.merchant_no, charge.order_no);
                                if (notifyResult != "OK")
                                {
                                    //创建通知消息对象
                                    _iPayNotifyService.Save(new pay_notify_dto
                                    {
                                        merchant_no = charge.merchant_no,
                                        order_no = charge.order_no,
                                        pay_channel = charge.pay_info.pay_channel,
                                        type = 1,
                                        status = 2,
                                        create_time = DateTime.Now
                                    });
                                }
                                _iPayHtmlService.Remove(id);
                            }
                        }
                    }
                    else
                    {
                        result = _iChargeService.PayFail(obj, model.merOrderId, model.resMsg);
                    }
                }
                else
                    return Content("success");
                //回执成功，通道不会再通知
                if (result > 0)
                {
                    return Content("success");
                }
                log.Info("xsft3-保存数据库订单失败:" + model.merOrderId);
                return Content("fail");
            }
            log.Info("xsft3-签名不正确:" + model.merOrderId);
            return Content("签名不正确");
        }

        [Route("cj_back_notify/{id}")]
        public async Task<ContentResult> CjPayNotify(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info($"畅捷异步通知了：{id}");
            var pay_notify = new cj_pay_notify();
            TryUpdateModel(pay_notify);
            var result = 0;
            var obj = _iPayHtmlService.Get(id);
            charge_dto charge = null;
            if (obj != null)
            {
                charge = obj.charge.ToObject<charge_dto>();
            }
            else
            {
                log.Info($"临时记录id:{id}找不到");
                return Content("fail");
            }

            if (pay_notify.status == 3)
            {
                var order = _iChargeService.GetByTran(pay_notify.transaction_no);
                if (order == null)
                {
                    result = _iChargeService.PaySuceess(obj, pay_notify.transaction_no, DateTime.Now);
                    if (result > 0)
                    {
                        var _iPayService = _iocContext.ResolveKeyed<IPayService>(charge.pay_info.pay_channel);
                        var notifyResult = await _iPayService.Notify(charge.merchant_no, charge.order_no);
                        if (notifyResult != "OK")
                        {
                            //创建通知消息对象
                            _iPayNotifyService.Save(new pay_notify_dto
                            {
                                merchant_no = charge.merchant_no,
                                order_no = charge.order_no,
                                pay_channel = charge.pay_info.pay_channel,
                                type = 1,
                                status = 2,
                                create_time = DateTime.Now
                            });
                        }
                        _iPayHtmlService.Remove(id);
                    }
                }
            }
            else
            {
                _iChargeService.PayFail(obj, pay_notify.transaction_no, pay_notify.result_msg);
                log.Info("支付失败");
                return Content("fail");
            }

            return Content("success");
        }
        /// <summary>
        /// 重新代付出款
        /// </summary>
        /// <returns></returns>
        [Route("ten_sub_re_pay")]
        public async Task<ContentResult> TenSubRePay()
        {
            var paySign = new TenSubPaySign();
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("腾付通分公司重新代付出款");
            var pay_notify = new ten_sub_payment();
            TryUpdateModel(pay_notify);
            log.Info($"接收参数：{pay_notify.ToJson()}");
            pay_notify.orderNo = DtoHelper.GenerateOrderNumber();
            pay_notify.merchantId = TenSubPaySign.mchid;
            pay_notify.amount = (Convert.ToInt32(pay_notify.amount) - Convert.ToInt32(pay_notify.rateAmount)).ToString();
            pay_notify.notifyUrl = "http://pay.timebiz.cn/ten_sub_payment_notify/" + pay_notify.notifyUrl;
            pay_notify.tradeName = "酒店预订";
            pay_notify.tradeTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            pay_notify.custBankAccountNo = paySign.encrypt(pay_notify.custBankAccountNo);
            pay_notify.custPhone = paySign.encrypt(pay_notify.custPhone);
            pay_notify.custID = paySign.encrypt(pay_notify.custID);
            pay_notify.custName = paySign.encrypt(pay_notify.custName);
            pay_notify.sourceIP = "60.205.220.14";
            var paymentResult = await paySign.PayGateway<ten_payment_res>(pay_notify, "/payapi/singlePrePayment");
            if (paymentResult != null)
            {
                if (paymentResult.data.status == "3")
                {
                    log.Info("请求代付接口成功");
                    return Content("success");
                }
            }
            return Content("fail");
        }
        /// <summary>
        /// 腾付通分公司支付回调接口
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("ten_sub_pay_notify/{id}")]
        public async Task<ContentResult> TenSubPayNotify(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info($"腾付通分公司异步通知了：{id}");
            var pay_notify = new ten_sub_pay_notify();
            TryUpdateModel(pay_notify);
            log.Info($"异步通知回执信息：{pay_notify.ToJson()}");
            var obj = _iPayHtmlService.Get(id);
            charge_dto charge = null;
            payment_data payment = null;
            if (obj != null)
            {
                charge = obj.charge.ToObject<charge_dto>();
                payment = obj.html.ToObject<payment_data>();
            }
            else
            {
                log.Info($"临时记录id:{id}找不到");
                return Content("fail");
            }

            var ten_query = new ten_sub_query
            {
                orderNo = pay_notify.orderNo,
                merchantId = TenSubPaySign.mchid,
                tradeType = "1"
            };
            TenSubPaySign tenSubPay = new TenSubPaySign();
            var resultApi = await tenSubPay.PayGateway<ten_sub_query_res>(ten_query, "/payapi/queryOrderInfo");
            if (resultApi != null)
            {
                if (resultApi.errorCode == "0000")
                {
                    if (resultApi.details.Count > 0)
                    {
                        var payInfo = resultApi.details[0];
                        if (payInfo.status == "0")
                        {
                            var order = _iChargeService.GetByTran(pay_notify.orderNo);
                            if (order == null)
                            {
                                var paySign = new TenSubPaySign();
                                var out_pay = new ten_sub_payment
                                {
                                    orderNo = pay_notify.orderNo,
                                    merchantId = TenSubPaySign.mchid,
                                    tradeName = "酒店预订",
                                    tradeTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
                                    amount = (Convert.ToInt32(pay_notify.amount) - Convert.ToInt32(pay_notify.rateAmount)).ToString(),
                                    custBankAccountNo = paySign.encrypt(payment.account_no),
                                    custPhone = paySign.encrypt(payment.mobile),
                                    custID = paySign.encrypt(payment.id_card),
                                    custName = paySign.encrypt(payment.account_name),
                                    sourceIP = "60.205.220.14",
                                    notifyUrl = $"http://pay.timebiz.cn/pay/ten_sub_payment_notify/" + id,
                                    rateAmount = pay_notify.rateAmount
                                };
                                var paymentResult = await paySign.PayGateway<ten_payment_res>(out_pay, "/payapi/singlePrePayment");
                                if (paymentResult != null)
                                {
                                    if (paymentResult.data.status == "3")
                                    {
                                        log.Info("请求代付接口成功");
                                        log.Info(out_pay.notifyUrl);
                                    }
                                }
                                else
                                {
                                    log.Info($"代付失败，异步通知回调id：{id},json:{pay_notify.ToJson()}");
                                    _iPayHtmlService.Update(id, "30");
                                }
                            }
                        }
                        else
                        {
                            _iChargeService.PayFail(obj, payInfo.orderNo, resultApi.failureDetails);
                            return Content("fail");
                        }
                    }
                }
                else
                {
                    _iChargeService.PayFail(obj, "", resultApi.failureDetails);
                    log.Info(resultApi.failureDetails);
                    return Content("fail");
                }
            }
            else
            {
                log.Info("请求查询接口/payapi/queryOrderInfo异常");
                return Content("fail");
            }

            return Content("ok");
        }
        /// <summary>
        /// 代付回调接口
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("ten_sub_payment_notify/{id}")]
        public async Task<ContentResult> TenSubPaymentNotify(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info($"腾付通分公司代付异步通知了：{id}");
            var pay_notify = new ten_payment_notify();
            TryUpdateModel(pay_notify);
            log.Info($"异步通知回执信息：{pay_notify.ToJson()}");
            int result = 0;
            var obj = _iPayHtmlService.Get(id);
            charge_dto charge = null;
            if (obj != null)
            {
                charge = obj.charge.ToObject<charge_dto>();
            }
            else
            {
                log.Info($"临时记录id:{id}找不到");
                return Content("fail");
            }

            if (pay_notify.status == "0")
            {
                var order = _iChargeService.GetByTran(pay_notify.orderNo);
                if (order == null)
                {
                    result = _iChargeService.PaySuceess(obj, pay_notify.orderNo, DateTime.Now);
                    if (result > 0)
                    {
                        var _iPayService = _iocContext.ResolveKeyed<IPayService>(charge.pay_info.pay_channel);
                        var notifyResult = await _iPayService.Notify(charge.merchant_no, charge.order_no);
                        if (notifyResult != "OK")
                        {
                            //创建通知消息对象
                            _iPayNotifyService.Save(new pay_notify_dto
                            {
                                merchant_no = charge.merchant_no,
                                order_no = charge.order_no,
                                pay_channel = charge.pay_info.pay_channel,
                                type = 1,
                                status = 2,
                                create_time = DateTime.Now
                            });
                        }
                        _iPayHtmlService.Remove(id);
                        log.Info("代付回调业务执行正常");
                    }
                    return Content("ok");
                }
            }

            return Content("fail");
        }

        /// <summary>
        /// 首信易网关支付同步回调通知
        /// </summary>
        /// <returns>The front.</returns>
        /// <param name="model">Model.</param>
        [Route("sxy_back_notify")]
        public async Task<ActionResult> SxyFront(sxy_gateway_result model)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("sxy同步通知了:" + model.ToJson());
            if (new SxyPaySign().VerifySign(model))
            {
                if (model.v_pstatus == "20")
                {
                    var result = 0;
                    var pay_html = _iPayHtmlService.Get(model.v_oid);
                    if (model.v_pstatus == "20")
                    {
                        if (pay_html.pay_type == "1")
                        {
                            result = _iOrderService.PaySuceess(pay_html, model.v_oid, DateTime.Now);
                            if (result > 0)
                            {
                                var charge = pay_html.charge.ToObject<charge_dto>();
                                var _iPayService = _iocContext.ResolveKeyed<IPayService>(charge.pay_info.pay_channel);
                                var notifyResult = await _iPayService.Notify(charge.merchant_no, charge.order_no);
                                if (notifyResult != "OK")
                                {
                                    //创建通知消息对象
                                    _iPayNotifyService.Save(new pay_notify_dto
                                    {
                                        merchant_no = charge.merchant_no,
                                        order_no = charge.order_no,
                                        pay_channel = charge.pay_info.pay_channel,
                                        type = 1,
                                        status = 2,
                                        create_time = DateTime.Now
                                    });
                                }
                                _iPayHtmlService.Remove(pay_html.id);
                                log.Info("易支付同步成功");
                            }
                        }
                        else if (pay_html.pay_type == "2")
                        {
                            result = _iOrderService.PayH5Success(pay_html, model.v_oid, DateTime.Now);
                            if (result > 0)
                            {
                                _iPayHtmlService.Remove(pay_html.id);
                                log.Info("h5易支付同步成功");
                            }
                        }
                    }
                    else
                    {
                        result = _iChargeService.PayFail(pay_html, model.v_oid, model.v_pstring);
                    }
                    return View("KltSuccess");
                }
            }
            return View("KltFail");
        }

        [Route("ltd_pay_notify")]
        public async Task<ContentResult> LtdPayNotify(ltd_notify model)
        {
            var result = "error";
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("ltd_pay_notify异步通知了：" + model.ToJson());
            bool is_pass = new LtdPaySign().VerifySign(model);
            if (!is_pass)
            {
                log.Info("ltd_pay_notify异步支付签名失败");
                return Content(result);
            }
            if (model.result_code != 1000 || model.status == 4)
            {
                log.Info("ltd_pay_notify异步支付失败信息：" + model.result_msg);
                return Content(result);
            }
            if (model.result_code == 1000 && model.status == 2)
            {
                var pay_html = _iPayHtmlService.Get(model.order_no);
                if (pay_html != null)
                {
                    var pay_result = _iChargeService.PaySuceess(pay_html, model.order_no, DateTime.Now);
                    if (pay_result > 0)
                    {
                        var charge = pay_html.charge.ToObject<charge_dto>();
                        var _ipayService = _iocContext.ResolveKeyed<IPayService>(charge.pay_info.pay_channel);
                        var notifyResult = await _ipayService.Notify(charge.merchant_no, charge.order_no);
                        if (notifyResult != "ok")
                        {
                            _iPayNotifyService.Save(new pay_notify_dto
                            {
                                merchant_no = charge.merchant_no,
                                order_no = charge.order_no,
                                pay_channel = charge.pay_info.pay_channel,
                                type = 1,
                                status = 2,
                                create_time = DateTime.Now
                            });
                        }
                        _iPayHtmlService.Remove(pay_html.id);
                        log.Info("ltd_pay_notify异步支付成功");
                        result = "success";
                    }
                }
            }
            return Content(result);
        }

        /// <summary>
        /// 易支付网关支付异步通知
        /// </summary>
        /// <returns>The pay notify.</returns>
        /// <param name="model">Model.</param>
        [Route("sxy_notify")]
        public async Task<ContentResult> SxyPayNotify(sxy_asyc_result model)
        {
            string result = "error";
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("sxy异步同步通知了:" + model.ToJson());
            SxyPaySign sxy = new SxyPaySign();
            if (sxy.AsycVerifySign(model))
            {
                log.Info("易支付指纹交易成功！");
                for (int i = 0; i < model.v_count; i++)
                {
                    var v_pstatus = StringHelper.SplitString(model.v_pstatus, "|_|");
                    var v_oids = StringHelper.SplitString(model.v_oid, "|_|");
                    result = await MultiOrderHandler(v_pstatus[i], v_oids[i]);
                }
            }
            return Content(result);
        }

        private async Task<string> MultiOrderHandler(string v_pstatus, string v_oid)
        {
            string result = "error";
            if (v_pstatus == "1")
            {
                var pay_html = _iPayHtmlService.Get(v_oid);
                if (pay_html.pay_type == "1")
                {
                    int status = _iOrderService.PaySuceess(pay_html, v_oid, DateTime.Now);
                    if (status > 0)
                    {
                        var charge = pay_html.charge.ToObject<charge_dto>();
                        var _iPayService = _iocContext.ResolveKeyed<IPayService>(charge.pay_info.pay_channel);
                        var notifyResult = await _iPayService.Notify(charge.merchant_no, charge.order_no);
                        if (notifyResult != "OK")
                        {
                            //创建通知消息对象
                            _iPayNotifyService.Save(new pay_notify_dto
                            {
                                merchant_no = charge.merchant_no,
                                order_no = charge.order_no,
                                pay_channel = charge.pay_info.pay_channel,
                                type = 1,
                                status = 2,
                                create_time = DateTime.Now
                            });
                        }
                        _iPayHtmlService.Remove(pay_html.id);
                        result = "sent";
                    }
                }
                else if (pay_html.pay_type == "2")
                {
                    int status = _iOrderService.PayH5Success(pay_html, v_oid, DateTime.Now);
                    if (status > 0)
                    {
                        _iPayHtmlService.Remove(pay_html.id);
                        result = "sent";
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// h5支付异步通知
        /// </summary>
        /// <returns>The pay notify.</returns>
        [Route("h5_pay_notify")]
        public ContentResult H5PayNotify()
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("h5支付异步回调通知...");
            ResponseHandler payNotifyRepHandler = new ResponseHandler(null);
            payNotifyRepHandler.SetKey(TenPayV3Info.Key);
            string attach = payNotifyRepHandler.GetParameter("attach");
            string return_code = payNotifyRepHandler.GetParameter("return_code");
            string return_msg = payNotifyRepHandler.GetParameter("return_msg");
            string xml = string.Format(@"<xml><return_code><![CDATA[{0}]]></return_code><return_msg><![CDATA[{1}]]></return_msg></xml>", return_code, return_msg);
            log.Info("return_code:" + return_code + ",attach=" + attach);
            if (return_code.ToUpper() != "SUCCESS")
            {
                return Content(xml, "text/xml");
            }

            string out_trade_no = payNotifyRepHandler.GetParameter("out_trade_no");
            string transaction_id = payNotifyRepHandler.GetParameter("transaction_id");
            log.Info("out_trade_no:" + out_trade_no + ",transaction_id：" + transaction_id);
            //验证请求是否从微信发过来（安全）
            if (payNotifyRepHandler.IsTenpaySign())
            {
                var _iPayService = _iocContext.ResolveKeyed<IMallBillService>(RequestMethod.TOKEN_NO);
                _iPayService.PaySuccess(attach, transaction_id, DateTime.Now);
            }
            return Content(xml, "text/xml");
        }
        /// <summary>
        /// 支付宝APP支付回调
        /// </summary>
        /// <returns></returns>
        [Route("alipay_notify/{id}")]
        public async Task<ContentResult> AlipayNotify(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("支付宝APP支付异步回调通知...");
            int i = 0;
            IDictionary<string, string> sArray = new Dictionary<string, string>();
            NameValueCollection coll;
            // Load  Form  variables  into  NameValueCollection  variable . 
            coll = Request.Form;
            //Get names of all forms into a string array . 
            var requestItem = coll.AllKeys;
            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
            }
            log.Info(sArray.ToJson());
            bool flag = AlipaySignature.RSACheckV1(sArray, AliPayV3Info.PublicKey, "UTF-8", "RSA2", false);
            if (flag)
            {
                log.Info("验签成功");
                var pay_html = _iPayHtmlService.Get(id);
                if (pay_html == null)
                {
                    log.Info("aliy-保存数据库订单失败");
                    return Content("fail");
                }
                int result = _iOrderService.PaySuceess(pay_html, sArray["trade_no"], DateTime.Now);
                if (result > 0)
                {
                    var charge = pay_html.charge.ToObject<charge_dto>();
                    var _iPayService = _iocContext.ResolveKeyed<IPayService>(charge.pay_info.pay_channel);
                    var notifyResult = await _iPayService.Notify(charge.merchant_no, charge.order_no);
                    if (notifyResult != "OK")
                    {
                        //创建通知消息对象
                        _iPayNotifyService.Save(new pay_notify_dto
                        {
                            merchant_no = charge.merchant_no,
                            order_no = charge.order_no,
                            pay_channel = charge.pay_info.pay_channel,
                            type = 1,
                            status = 2,
                            create_time = DateTime.Now
                        });
                    }
                    _iPayHtmlService.Remove(id);
                }
                //回执成功，通道不会再通知
                if (result > 0)
                {
                    return Content("ok");
                }
                return Content("fail");
            }

            return Content("ok");
        }
        /// <summary>
        /// 内网测试支付成功异步回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("token_pay_success/{id}")]
        public string TokenPaySuccess(string id)
        {
            var transaction_id = "89900000";
            var _iPayService = _iocContext.ResolveKeyed<IMallBillService>(RequestMethod.TOKEN_NO);
            _iPayService.PaySuccess(id, transaction_id, DateTime.Now);
            return "ok";
        }
        /// <summary>
        /// 手动补单
        /// </summary>
        /// <param name="pay_no"></param>
        /// <param name="transaction_no"></param>
        /// <returns></returns>
        [Route("token_hand_pay"), HttpGet, AllowAnonymous]
        public string TokenHandPaySuccess(string pay_no, string transaction_no)
        {
            var _iPayService = _iocContext.ResolveKeyed<IMallBillService>(RequestMethod.TOKEN_NO);
            _iPayService.PaySuccess(pay_no, transaction_no, DateTime.Now);
            return "ok";
        }

        /// <summary>
        /// HF扫码同步请求
        /// </summary>
        /// <returns>The native front notify.</returns>
        /// <param name="model">Identifier.</param>
        [Route("hf_native_front_notify/{id}")]
        public ActionResult HfNativeFrontNotify(JObject model, string id)
        {
            //lock (sequenceLock) {
            //	var _hfSign = new HfSign();
            //	var data = model.ToObject<pay_native_notify>();
            //	if (_hfSign.VerifySign(model, data.sign, id)) {
            //		var result = 0;
            //		if (data.returnCode == "0" && data.resultCode == "0") {
            //			var order = _iChargeService.GetByTran(data.channelOrderNo);
            //			if (data.status == "02" && data.amount == order.pay_amount) {
            //				var dt = data.transTime.ToDateTime();
            //				if (order.status != ChargeStatus.Finish)
            //					result = _iChargeService.FailOrUnConfirmToSuceess(order.merchant_no, data.outTradeNo, dt);
            //			}
            //			//回执成功，通道不会再通知
            //			if (result > 0) {
            //				if (!string.IsNullOrEmpty(order.front_notify))
            //					return Redirect(order.front_notify);
            //				return View("OK");
            //			}
            //		}
            //		return View("FAIL");
            //	}
            //	return View("签名不正确");
            //}
            return View("OK");
        }

        /// <summary>
        /// 获取微信code授权码
        /// </summary>
        /// <param name="code"></param>
        /// <param name="from"></param>
        /// <returns></returns>
        [Route("wx_code")]
        public async Task<ActionResult> WechatLoginGetCode(string code = "", string from = "")
        {
            var result = await Core.WeiXin.OAuthApi.GetAccessToken(RequestMethod.WX_PUB_APP_ID, RequestMethod.WX_PUB_APP_SECRET, code);
            var url = Server.UrlDecode(from);
            if (string.IsNullOrWhiteSpace(url))
            {
                return RedirectToAction("Pay", "OpenError");
            }
            else
            {
                return Redirect(url + "&openid=" + result.openid);
            }
        }

        /// <summary>
        /// 传话批量代付异步通知
        /// </summary>
        /// <returns>The pay transfer notify.</returns>
        [Route("chpay_batchtransfer_notify")]
        public async Task<ActionResult> ChPayTransferBatchNotify()
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("chpay批量代付异步通知了");
            var model = new cn_transferbatch_notify();
            TryUpdateModel(model);
            log.Info("chpay批量号:" + model.batchno);
            var _chpaySign = new ChPaySign();
            if (_chpaySign.VerifySign(model))
            {
                log.Info("chpay批量代付异步通知成功:" + model.batchno);
                var result = 0;
                var batch = _iTransferService.GetBatch(model.batchno);
                if (batch != null && batch.status != TransferBatchStatus.Treat)
                {
                    var _iPayService = _iocContext.ResolveKeyed<IPayService>(PayChannel.ChPay);
                    string transferResult = model.successdetails + "|" + model.faildetails;
                    log.Info(transferResult);
                    result = await _iPayService.TransferNotify(batch.id, transferResult, 0);
                    //回执成功，通道不会再通知
                    if (result > 0)
                        return Json(new { result = "success", msg = "请求成功" }, JsonRequestBehavior.AllowGet);
                }
                else
                    return Json(new { result = "error", msg = "请求失败" }, JsonRequestBehavior.AllowGet);
            }
            log.Info("chpay-签名不正确:");
            return Json(new { result = "error", msg = "签名不正确" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 传话代付异步通知
        /// </summary>
        /// <returns>The pay transfer notify.</returns>
        /// <param name="id">Identifier.</param>
        [Route("chpay_transfer_notify/{id}")]
        public async Task<ActionResult> ChPayTransferNotify(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("chpay代付异步通知了:" + id);
            var model = new ch_transfer_notify();
            TryUpdateModel(model);
            string merchant_no = id;
            var _chpaySign = new ChPaySign();
            if (_chpaySign.VerifySign(model))
            {
                log.Info("chpay代付异步通知成功:" + model.businessnumber);
                var result = 0;
                var transfer = _iTransferService.GetByPayNo(merchant_no, model.businessnumber);
                if (transfer != null)
                {
                    var pay_time = DateTime.Parse(model.inputdate);
                    if (model.status == "成功")
                    {
                        result = _iTransferService.TransferSuccess(new platform_transfer
                        {
                            pay_time = pay_time,
                            transaction_no = model.businessrecordnumber,
                            status = TransferStatus.Finish,
                            merchant_no = merchant_no,
                            order_no = transfer.order_no
                        });
                        if (result > 0)
                        {
                            var _iPayService = _iocContext.ResolveKeyed<IPayService>(transfer.pay_info.pay_channel);
                            var notifyResult = await _iPayService.NotifyTransfer(merchant_no, transfer.order_no);
                            if (notifyResult != "OK")
                            {
                                //创建通知消息对象
                                _iPayNotifyService.Save(new pay_notify_dto
                                {
                                    merchant_no = merchant_no,
                                    order_no = transfer.order_no,
                                    pay_channel = transfer.pay_info.pay_channel,
                                    type = 2,
                                    status = (int)TransferStatus.Finish,
                                    create_time = DateTime.Now
                                });
                            }
                        }
                    }
                    else
                    {
                        string fail = !string.IsNullOrEmpty(model.remark) ? model.remark : "代付失败";
                        result = _iTransferService.TransferFail(new platform_transfer
                        {
                            pay_time = pay_time,
                            transaction_no = model.businessrecordnumber,
                            merchant_no = merchant_no,
                            status = TransferStatus.Fail,
                            order_no = transfer.order_no,
                            fail = fail
                        });
                    }
                }
                else
                {
                    log.Info("chpay-请求失败:" + model.businessnumber);
                    return Json(new { result = "error", msg = "请求失败" }, JsonRequestBehavior.AllowGet);
                }
                //回执成功，通道不会再通知
                if (result > 0)
                {
                    return Json(new { result = "success", msg = "请求成功" }, JsonRequestBehavior.AllowGet);
                }
                log.Info("chpay-保存数据库订单失败:" + model.businessnumber);
                return Json(new { result = "error", msg = "请求失败" }, JsonRequestBehavior.AllowGet);
            }
            log.Info("chpay-签名不正确:");
            return Json(new { result = "error", msg = "签名不正确" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 传话代付异步通知,手动提现
        /// </summary>
        /// <returns>The pay transfer notify.</returns>
        /// <param name="id">Identifier.</param>
        [Route("chpay_transfer_notify2/{id}")]
        public async Task<ActionResult> ChPayTransferNotify2(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("chpay代付异步通知了:" + id);
            var model = new ch_transfer_notify();
            TryUpdateModel(model);
            string merchant_no = id;
            var _chpaySign = new ChPaySign();
            log.Info("chpay代付异步通知成功:" + model.businessnumber);
            var result = 0;
            var transfer = _iTransferService.GetByPayNo(merchant_no, model.businessnumber);
            if (transfer != null)
            {
                var pay_time = DateTime.Parse(model.inputdate);
                if (model.status == "成功")
                {
                    result = _iTransferService.TransferSuccess(new platform_transfer
                    {
                        pay_time = pay_time,
                        transaction_no = model.businessrecordnumber,
                        status = TransferStatus.Finish,
                        merchant_no = merchant_no,
                        order_no = transfer.order_no
                    });
                    if (result > 0)
                    {
                        var _iPayService = _iocContext.ResolveKeyed<IPayService>(transfer.pay_info.pay_channel);
                        var notifyResult = await _iPayService.NotifyTransfer(merchant_no, transfer.order_no);
                        if (notifyResult != "OK")
                        {
                            //创建通知消息对象
                            _iPayNotifyService.Save(new pay_notify_dto
                            {
                                merchant_no = merchant_no,
                                order_no = transfer.order_no,
                                pay_channel = transfer.pay_info.pay_channel,
                                type = 2,
                                status = (int)TransferStatus.Finish,
                                create_time = DateTime.Now
                            });
                        }
                    }
                }
                else
                {
                    string fail = !string.IsNullOrEmpty(model.remark) ? model.remark : "代付失败";
                    result = _iTransferService.TransferFail(new platform_transfer
                    {
                        pay_time = pay_time,
                        transaction_no = model.businessrecordnumber,
                        merchant_no = merchant_no,
                        status = TransferStatus.Fail,
                        order_no = transfer.order_no,
                        fail = fail
                    });
                }
            }
            else
            {
                log.Info("chpay-请求失败:" + model.businessnumber);
                return Json(new { result = "error", msg = "请求失败" }, JsonRequestBehavior.AllowGet);
            }
            //回执成功，通道不会再通知
            if (result > 0)
            {
                return Json(new { result = "success", msg = "请求成功" }, JsonRequestBehavior.AllowGet);
            }
            log.Info("chpay-保存数据库订单失败:" + model.businessnumber);
            return Json(new { result = "error", msg = "请求失败" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// token提现代付异步通知
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("chpay_token_transfer_notify/{id}")]
        public async Task<ActionResult> ChPayTokenTransferNotify(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("token-chpay代付异步通知了:" + id);
            var model = new ch_transfer_notify();
            TryUpdateModel(model);
            string merchant_no = id;
            var _chpaySign = new ChPaySign();
            if (_chpaySign.VerifySign(model))
            {
                log.Info("token-chpay代付异步通知成功:" + model.businessnumber);
                var result = 0;
                var transfer = _iTokenTransferService.GetByPayNo(merchant_no, model.businessnumber);
                if (transfer == null)
                {
                    log.Info("token-chpay-请求失败:" + model.businessnumber);
                    return Json(new { result = "error", msg = "请求失败" }, JsonRequestBehavior.AllowGet);
                }
                var pay_time = DateTime.Parse(model.inputdate);
                if (model.status == "成功")
                {
                    result = _iTokenTransferService.TransferSuccess(new platform_transfer
                    {
                        pay_time = pay_time,
                        transaction_no = model.businessrecordnumber,
                        status = TransferStatus.Finish,
                        merchant_no = merchant_no,
                        order_no = transfer.order_no,
                        transfer_type = transfer.transfer_type
                    });
                    var _iPayService = _iocContext.ResolveKeyed<IPayService>(transfer.pay_info.pay_channel);
                    var notifyResult = await _iPayService.NotifyTransfer(merchant_no, transfer.order_no);
                    if (notifyResult != "OK")
                    {
                        //创建通知消息对象
                        _iPayNotifyService.Save(new pay_notify_dto
                        {
                            merchant_no = merchant_no,
                            order_no = transfer.order_no,
                            pay_channel = transfer.pay_info.pay_channel,
                            type = 2,
                            status = (int)TransferStatus.Finish,
                            create_time = DateTime.Now
                        });
                    }
                }
                else
                {
                    string fail = !string.IsNullOrEmpty(model.remark) ? model.remark : "代付失败";
                    result = _iTokenTransferService.TransferFail(new platform_transfer
                    {
                        pay_time = pay_time,
                        transaction_no = model.businessrecordnumber,
                        merchant_no = merchant_no,
                        status = TransferStatus.Fail,
                        order_no = transfer.order_no,
                        fail = fail,
                        transfer_type = transfer.transfer_type
                    });
                }
                //回执成功，通道不会再通知
                if (result > 0)
                {
                    return Json(new { result = "success", msg = "请求成功" }, JsonRequestBehavior.AllowGet);
                }
                log.Info("token-chpay-保存数据库订单失败:" + model.businessnumber);
                return Json(new { result = "error", msg = "请求失败" }, JsonRequestBehavior.AllowGet);
            }
            log.Info("token-chpay签名不正确:");
            return Json(new { result = "error", msg = "签名不正确" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// token提现代付异步通知,手动提现
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("chpay_token_transfer_notify2/{id}")]
        public async Task<ActionResult> ChPayTokenTransferNotify2(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("token-chpay代付异步通知了:" + id);
            var model = new ch_transfer_notify();
            TryUpdateModel(model);
            string merchant_no = id;
            var _chpaySign = new ChPaySign();
            log.Info("token-chpay代付异步通知成功:" + model.businessnumber);
            var result = 0;
            var transfer = _iTokenTransferService.GetByPayNo(merchant_no, model.businessnumber);
            if (transfer == null)
            {
                log.Info("token-chpay-请求失败:" + model.businessnumber);
                return Json(new { result = "error", msg = "请求失败" }, JsonRequestBehavior.AllowGet);
            }
            var pay_time = DateTime.Parse(model.inputdate);
            if (model.status == "成功")
            {
                result = _iTokenTransferService.TransferSuccess(new platform_transfer
                {
                    pay_time = pay_time,
                    transaction_no = model.businessrecordnumber,
                    status = TransferStatus.Finish,
                    merchant_no = merchant_no,
                    order_no = transfer.order_no,
                    transfer_type = transfer.transfer_type
                });
                var _iPayService = _iocContext.ResolveKeyed<IPayService>(transfer.pay_info.pay_channel);
                var notifyResult = await _iPayService.NotifyTransfer(merchant_no, transfer.order_no);
                if (notifyResult != "OK")
                {
                    //创建通知消息对象
                    _iPayNotifyService.Save(new pay_notify_dto
                    {
                        merchant_no = merchant_no,
                        order_no = transfer.order_no,
                        pay_channel = transfer.pay_info.pay_channel,
                        type = 2,
                        status = (int)TransferStatus.Finish,
                        create_time = DateTime.Now
                    });
                }
            }
            else
            {
                string fail = !string.IsNullOrEmpty(model.remark) ? model.remark : "代付失败";
                result = _iTokenTransferService.TransferFail(new platform_transfer
                {
                    pay_time = pay_time,
                    transaction_no = model.businessrecordnumber,
                    merchant_no = merchant_no,
                    status = TransferStatus.Fail,
                    order_no = transfer.order_no,
                    fail = fail,
                    transfer_type = transfer.transfer_type
                });
            }
            //回执成功，通道不会再通知
            if (result > 0)
            {
                return Json(new { result = "success", msg = "请求成功" }, JsonRequestBehavior.AllowGet);
            }
            log.Info("token-chpay-保存数据库订单失败:" + model.businessnumber);
            return Json(new { result = "error", msg = "请求失败" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 闵汇异步通知
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("mpay_native_notify/{id}")]
        public async Task<ActionResult> MihuiNotify(string id)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("mpay异步通知了:" + id);
            var stream = Request.InputStream;
            var streamReader = new StreamReader(stream);
            var data = streamReader.ReadToEnd();
            log.Info("mpay异步通知数据:" + data);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var arrs = data.Split('&');
            foreach (var arr in arrs)
            {
                var val = arr.Split('=');
                if (val[0] == "resMsg")
                    dic.Add(val[0], Server.UrlDecode(val[1]));
                else
                    dic.Add(val[0], val[1]);
            }
            var model = dic.ToJson().ToObject<mpay_notice>();

            log.Info("mpay异步同步通知了:" + model.ToJson());
            MpaySign mpaySign = new MpaySign();
            if (mpaySign.VerifySign(model))
            {
                log.Info("mpay异步通知成功:" + model.orrderId);
                var result = 0;
                var obj = _iPayHtmlService.Get(id);
                charge_dto charge = null;
                if (obj != null)
                {
                    charge = obj.charge.ToObject<charge_dto>();
                }
                else
                {
                    log.Info("mpay－mongodb获取失败:" + model.orrderId);
                    return Content("fail");
                }
                var order = _iChargeService.Get(charge.merchant_no, model.orrderId);
                //因为同进同出HTML的生成是用mongodb，所以要查数据库订单生成了没有，没有生成则调用返回参数处理
                if (order == null)
                {
                    if (model.status == "S")
                    {
                        var dt = DateTime.Now;
                        result = _iChargeService.PaySuceess(obj, model.orrderId, dt);
                        if (result > 0)
                        {
                            var _iPayService = _iocContext.ResolveKeyed<IPayService>(charge.pay_info.pay_channel);
                            var notifyResult = await _iPayService.Notify(charge.merchant_no, charge.order_no);
                            if (notifyResult != "OK")
                            {
                                //创建通知消息对象
                                _iPayNotifyService.Save(new pay_notify_dto
                                {
                                    merchant_no = charge.merchant_no,
                                    order_no = charge.order_no,
                                    pay_channel = charge.pay_info.pay_channel,
                                    type = 1,
                                    status = 2,
                                    create_time = DateTime.Now
                                });
                            }
                            _iPayHtmlService.Remove(id);
                        }
                    }
                    else
                    {
                        result = _iChargeService.PayFail(obj, model.orrderId);
                    }
                }
                else
                    return Content("success");
                //回执成功，通道不会再通知
                if (result > 0)
                {
                    return Content("success");
                }
                log.Info("mpay-保存数据库订单失败:" + model.orrderId);
                return Content("fail");
            }
            log.Info("mpay-签名不正确:" + model.orrderId);
            return Content("签名不正确");
        }
        /// <summary>
        /// 同步海淘乐商品
        /// </summary>
        /// <param name="product_req"></param>
        /// <returns></returns>
        [Route("accept_products")]
        [ValidateInput(false)]
        public ContentResult AcceptProducts(htl_product_req product_req)
        {
            var log = IocHelper.Get<ILogHelper>("info");
            log.Info("同步海淘乐商品:" + product_req.ToJson());
            //var result = _iHtlMallService.PullProduct(product_req);
            log.Info("同步海淘乐数据成功...");
            return Content("");
        }
        /// <summary>
        /// 接收候鸟推送数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("accept_hniao_data")]
        [ValidateInput(false)]
        public async Task<ContentResult> AcceptHniaoData()
        {
            var log = IocHelper.Get<ILogHelper>("info");
            var stream = Request.InputStream;
            var streamReader = new StreamReader(stream);
            var data = streamReader.ReadToEnd();
            data = WebHelper.UrlDecode(data);
            log.Info("同步候鸟数据：" + data);
            var model = data.ToObject<hn_notify_base>();
            var result = await _iHniaoService.PullGoods(model);
            log.Info("同步候鸟数据成功...");
            return Content("success");
        }

        [Route("h5")]
        public async Task<ContentResult> ShiDaiPay()
        {
            h5_token_req req = new h5_token_req
            {
                client_id = "468aee69610a31850a41213637643f50",
                client_secret = "36af41dcb774416e861af8f2c5d9b025"
            };
            var authToken = await _h5Sign.GetAuthToken(req);
            var token = authToken.access_token;

            var result = await _h5Sign.GetPay(token);
            return Content("");
        }
    }
}
